// ignore_for_file: non_constant_identifier_names

import 'package:commons/commons.dart';
import 'state.dart';
export 'encryption.dart';

extension UserControllerEx on GetInterface {
  UserController get userCtrl => Get.find<UserController>();
}

class UserController extends GetxController {
  final state = UserState();

  final key_store_user = 'key_store_user';
  final key_store_account = 'key_store_account';
  final key_store_pwd = 'key_store_pwd';
  final key_store_user_token = 'key_store_user_token';

  String? loginAccount;
  String? loginPwd;

  Future<void> initData() async {
    String token = Get.storage.get(key_store_user_token);
    if (token.isEmpty) {
      return;
    }
    loginAccount = Get.storage.get(key_store_account);
    loginPwd = Get.storage.get(key_store_pwd);

    var user = Get.storage.getModel<UserModel>(
      key_store_user,
      (j) => UserModel.fromJson(j),
    );
    if (user != null) {
      configUser(user);
      if (isLogin) {}
    }
  }

  Future<void> loginSuccess(UserModel user) async {
    configUser(user);
    // UmMan().onSignIn(state.user!.userId!);
    await save();
  }

  Future<void> loginOutSuccess() async {
    // isLogin = false;

    // EMClient.getInstance.chatManager.fetchHistoryMessages(conversationId)
    isLogin = false;
    state.token = null;
    // UmMan().onSignOut();
    await Get.storage.remove(key_store_user_token);
    await Get.storage.remove(key_store_account);
    await Get.storage.remove(key_store_pwd);
  }

  void updateAvater(String avater) {
    if (state.user == null) {
      return;
    }
    // state.user?.updateAvater(avater);

    loginSuccess(state.user!);
  }

  void configUser(UserModel user) {
    isLogin = true;
    state.user = user;
    state.token = user.utoken;
    state.userObs.value = state.user!;
    state.userObs.refresh();
  }

  final isLoginObs = false.obs;
  set isLogin(bool value) {
    isLoginObs.value = value;
    if (value == false) {
      Get.storage.remove(key_store_user_token);
    }
  }

  bool get isLogin {
    return state.token?.isNotEmpty == true;
  }

  final isAtLoginObs = true.obs;
  set isAtLogin(bool value) => isAtLoginObs.value = value;
  bool get isAtLogin => isAtLoginObs.value;

  Future<bool> save() async {
    if (state.user != null) {
      var json = state.user!.toJson();
      await Get.storage.setJson(key_store_user, json);
      await Get.storage.set(key_store_user_token, state.token!);
      return true;
    }
    return false;
  }

  Future<void> saveLogin({required String account, required String pwd}) async {
    loginAccount = account;
    loginPwd = pwd;
    await Get.storage.set(key_store_account, account);
    await Get.storage.set(key_store_pwd, pwd);
  }
}
